package com.ghc.boot;

import com.ghc.NettyApplication;
import com.ghc.client.CuratorClient;
import com.ghc.handler.UserServiceHandler;
import com.ghc.serializer.JSONSerializer;
import com.ghc.serializer.RpcDecoder;
import com.ghc.serializer.RpcEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.springframework.context.annotation.Bean;

public class ServerBoot {

    /*public static void main(String[] args) throws InterruptedException {
        startServer("127.0.0.1", "8999");
    }*/

    public static void startServer(String ip, String port) throws Exception {
        //1、创建两个线程池对象
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        //2、创建服务端的启动引导对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workGroup)
                //设置通道为NIO
                .channel(NioServerSocketChannel.class)
                //创建监听channel
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        pipeline.addLast(new RpcEncoder(Object.class, new JSONSerializer()));
                        pipeline.addLast(new RpcDecoder(Object.class, new JSONSerializer()));
                        //把我们自定义的CHannelHander添加到通道中
                        pipeline.addLast(new UserServiceHandler());
                    }
                });

        serverBootstrap.bind(Integer.parseInt(port)).sync();
        connectZookeeper();
    }

    /**
     * 连接zookeeper 创建创建节点
     */
    public static void connectZookeeper() throws Exception {

        RetryPolicy exponentialBackoffRetry = new ExponentialBackoffRetry(1000, 3);
        //使用fluent变成风格
        CuratorFramework curatorClient = CuratorFrameworkFactory.builder()
                .connectString("127.0.0.1:2181")
                .sessionTimeoutMs(1000)
                .connectionTimeoutMs(3000)
                .retryPolicy(exponentialBackoffRetry)
                .namespace("base")  //独立的命名空间
                .build();
        curatorClient.start();

        String s = curatorClient.create().creatingParentContainersIfNeeded()
                .withMode(CreateMode.EPHEMERAL).forPath(CuratorClient.path + "/" + NettyApplication.port, String.valueOf(System.currentTimeMillis()).getBytes());
        System.out.println("节点递归创建成功， 节点路径： " + s);

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try {
                        Stat stat = new Stat();
                        curatorClient.getData().storingStatIn(stat).forPath(CuratorClient.path + "/" + NettyApplication.port);
                        curatorClient.setData().withVersion(stat.getVersion()).forPath(CuratorClient.path + "/" + NettyApplication.port, String.valueOf(System.currentTimeMillis()).getBytes());
                        Thread.sleep(5000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        thread.start();
    }
}
